/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mrp.productionPlanning.managedbean;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import mrp.productionPlanning.entity.DailyDetailEntity;
import mrp.productionPlanning.entity.HolidayEntity;
import mrp.productionPlanning.session.DailyDetailSessionBean;
import mrp.productionPlanning.session.HolidaySessionBean;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

/**
 *
 * @author Wei Haoyang
 */
@ManagedBean
@ViewScoped
public class SetHolidaysManagedBean {
    @Resource(name = "merlionFoodERPDataSource")
    private DataSource merlionFoodERPDataSource;
    @EJB
    HolidaySessionBean hsb = new HolidaySessionBean();
    @EJB
    DailyDetailSessionBean ddsb;
    private List<HolidayEntity> holidayList = new ArrayList<HolidayEntity>();
    private HolidayEntity holiday = new HolidayEntity();
    
    private StreamedContent file;
    private boolean view = false;
    
    
    /** Creates a new instance of SetHolidaysManagedBean */
    public SetHolidaysManagedBean() {
    }
    
    public void addHoliday(ActionEvent event){
        holidayList.add(holiday);
        holiday = new HolidayEntity();
    }
    
    public void deleteHoliday(HolidayEntity h){
        int id = 0;
        
        for (int i = 0; i < holidayList.size(); i++){
            if (holidayList.get(i).getName().equals(h.getName()))
                id = i;
        }
        holidayList.remove(id);
    }
            
    public void submitRecord(ActionEvent event){
        DailyDetailEntity day = new DailyDetailEntity();
        for (HolidayEntity h:holidayList){
            hsb.addHolidayDay(h);
            day = ddsb.getDailyDetailByDate(h.getDate());
            if (day != null){
                ddsb.removeDailyDetail(day);
            System.out.println("Day removed: "+ day.getDate().toString());
            }
        }
        
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Set Holiday Successful!", ""));
    }

    public void exportToPDFBySQLConn(ActionEvent event){
        try {
            String strSQL = "SELECT h.DATE, h.NAME FROM HOLIDAYENTITY h";
            ResultSet rsEvents = merlionFoodERPDataSource.getConnection().prepareStatement(strSQL).executeQuery();
            JRResultSetDataSource jrResultSetDataSource = new JRResultSetDataSource(rsEvents);
           
            String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("jasperreports");
            
            HashMap parameters = new HashMap();
            parameters.put("IMAGEPATH", "http://localhost:8080/MerlionFoodERP-war/jasperreports/wood.jpg");
            String fileName = path+"/holiday.jasper";
            String outFileName = path+"/Holidays.pdf";
            // Fill the report using an empty data source
            JasperPrint print = JasperFillManager.fillReport(fileName, parameters, jrResultSetDataSource);
            
            // Create a PDF exporter
            JRExporter exporter = new JRPdfExporter();
            
            // Configure the exporter (set output file name and print object)
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, outFileName);
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            
            // Export the PDF file
            exporter.exportReport();
            setView(true);
            
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Report generated successfully.", ""));
        }
        catch (JRException jrex){
            System.out.println("********** Jasperreport Exception");
            jrex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "There is something wrong...", ""));
        }
        catch (Exception ex){
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "There is something wrong...", ""));
        }
    }
    
    public StreamedContent getFile() throws IOException {
        InputStream stream = ((HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true)).getServletContext().getResourceAsStream("/jasperreports/Holidays.pdf");
        
        if (stream == null){
            System.out.println("************Cannot find file.");
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "The report has not been generated yet", ""));
        }
        setFile(new DefaultStreamedContent(stream, "application/pdf","downloadFile.pdf"));
        return this.file;
    }
    
    public List<HolidayEntity> getHolidayList() {
        return holidayList;
    }

    public void setHolidayList(List<HolidayEntity> holidayList) {
        this.holidayList = holidayList;
    }

    public HolidayEntity getHoliday() {
        return holiday;
    }

    public void setHoliday(HolidayEntity holiday) {
        this.holiday = holiday;
    }

    public void setFile(StreamedContent file) {
        this.file = file;
    }

    public boolean isView() {
        return view;
    }

    public void setView(boolean view) {
        this.view = view;
    }
    
    
    
}
